package com.gzxw.mogublog.web.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gzxw.mogublog.base.global.BaseSysConf;
import com.gzxw.mogublog.base.holder.RequestHolder;
import com.gzxw.mogublog.commons.entity.Admin;
import com.gzxw.mogublog.commons.entity.Blog;
import com.gzxw.mogublog.commons.entity.File;
import com.gzxw.mogublog.commons.feign.PictureFeignClient;
import com.gzxw.mogublog.utils.IpUtils;
import com.gzxw.mogublog.utils.R;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.utils.global.Constants;
import com.gzxw.mogublog.xo.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/content")
public class BlogContentController {

    @Value(value = "${BLOG.ORIGINAL_TEMPLATE}")
    private String ORIGINAL_TEMPLATE;
    @Value(value = "${BLOG.REPRINTED_TEMPLATE}")
    private String REPRINTED_TEMPLATE;

    @Autowired
    private BlogService blogService;

    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/getBlogByUid")
    public R getBlogByUid(@RequestParam(value = "uid",required = false) String uid,
                          @RequestParam(value = "oid",required = false) String oid) {

        HttpServletRequest request = RequestHolder.getRequest();
        String ip = IpUtils.getIpAddr(request);

        Blog blog = null;
        if (StringUtils.isNotEmpty(uid)) {
            blog = blogService.getById(uid);
        } else {
            QueryWrapper<Blog> blogQueryWrapper = new QueryWrapper<>();
            blogQueryWrapper.eq("oid", oid);
            blogQueryWrapper.last("limit 1");
            blog = blogService.getOne(blogQueryWrapper);
        }

        if (blog == null || blog.getStatus() == 0 || "0".equals(blog.getIsPublish())) {
            return R.error("200", "博客被下架或删除");
        }

        // 设置文章版权申明
        setBlogCopyright(blog);

        // 为博客设置标签
        blogService.setTagByBlog(blog);

        // 获取分类
        blogService.setSortByBlog(blog);

        // 设置标题图
        setPhotoListByBlog(blog);

        // 从Redis取出数据，判断该用户是否点击过
        String jsonResult = stringRedisTemplate.opsForValue().get("BLOG_CLICK:" + ip + "#" + blog.getUid());

        if (StringUtils.isEmpty(jsonResult)) {
            // 博客的点击量增加
            Integer count = blog.getClickCount() + 1;
            blog.setClickCount(count);
            blog.updateById();

            // 将用户的点击数放入redis中
            stringRedisTemplate.opsForValue().set("BLOG_CLICK" + ":" + ip + "#" + blog.getUid(), blog.getClickCount().toString(), 24, TimeUnit.HOURS);

        }

        return R.success("返回成功", blog);
    }

    // 通过Uid获取博客点赞数
    @GetMapping("/getBlogPraiseCountByUid")
    public R getBlogPraiseCountByUid(@RequestParam(name = "uid", required = false) String uid) {

        Integer praiseCount = blogService.getBlogPraiseCountByUid(uid);

        return R.success("返回成功",praiseCount);
    }

    // 给博客点赞
    @GetMapping("/praiseBlogByUid")
    public R praiseBlogByUid(@RequestParam(value = "uid",required = false) String uid) {

        String message = blogService.praiseBlogByUid(uid);

        return R.success("200",message);
    }

    // 根据标签Uid获取相关的博客
    @GetMapping("/getSameBlogByTagUid")
    public R getSameBlogByTagUid(@RequestParam(value = "tagUid",required = false) String tagUid,
                                 @RequestParam(value = "currentPage",required = false) Long currentPage,
                                 @RequestParam(value = "pageSize",required = false) Long pageSize) {

       IPage<Blog> pageList = blogService.getSameBlogByTagUid(tagUid);
        Map<String, Object> result = new HashMap<>();
        List<Blog> records = pageList.getRecords();
        long total = pageList.getTotal();
        long size = pageList.getSize();
        long current = pageList.getCurrent();
        result.put("records", records);
        result.put("total", total);
        result.put("size", size);
        result.put("current", current);

        return  R.success("返回成功",result);
    }

    @GetMapping("/getSameBlogByBlogUid")
    public R getSameBlogByBlogUid(@RequestParam(value = "blogUid",required = true)String blogUid) {

        IPage<Blog> pageList = blogService.getSameBlogByBlogUid(blogUid);
        Map<String, Object> result = new HashMap<>();
        List<Blog> records = pageList.getRecords();
        long total = pageList.getTotal();
        long size = pageList.getSize();
        long current = pageList.getCurrent();
        result.put("records", records);
        result.put("total", total);
        result.put("size", size);
        result.put("current", current);

        return R.success("返回成功",result);
    }



    private void setBlogCopyright(Blog blog) {
        //如果是原创的话
        if (Constants.STR_ONE.equals(blog.getIsOriginal())) {
            blog.setCopyright(ORIGINAL_TEMPLATE);
        } else {
            String reprintedTemplate = REPRINTED_TEMPLATE;
            String[] variable = {blog.getArticlesPart(), blog.getAuthor()};
            String str = String.format(reprintedTemplate, variable);
            blog.setCopyright(str);
        }
    }

    private void setPhotoListByBlog(Blog blog) {
        //获取标题图片
        if (blog != null && !StringUtils.isEmpty(blog.getFileUid())) {
            R picResult = pictureFeignClient.getPicture(blog.getFileUid());
            String message = picResult.getMessage();
            File file = JSON.parseObject(message, File.class);
            if (file != null) {
                blog.setPhotoList(Collections.singletonList(file.getPicUrl()));
                blog.setPhotoUrl(file.getPicUrl());
            }

        }
    }

}
